
# 表示我们的会员入口
# 所有都使用我们的route_api进行统一注解
from web.controllers.api import route_api
from flask import request,jsonify,g
from application import app,db
# 引入登录信息
from common.models.member.Member import Member
from common.models.member.OauthMemberBind import OauthMemberBind
import requests,json
from common.libs.Helper import getCurrentDate
from common.libs.member.MemberService import MemberService
from common.models.food.WxShareHistory import WxShareHistory

# 开始订餐
# login方法由我们的code信息来获取openid，再由openid把我们的member表和绑定信息表进行映射关联字段。
# 再由member表注册进来，再返回token信息到我们的小程序系统，
@route_api.route("/member/login",methods = ["GET","POST"])
def login():
    resp ={'code':200, 'msg':'操作成功','data':{}}
    # 从request.values里面得到变量
    req = request.values

    openid = req['openid'] if 'openid' in req else ''

    # 将所有后台信息进行统一展示 : 通过code可以获取用户的基本信息（session_key、openid）
    # code =req['code'] if 'code' in req else ''
    # if not code or len(code) <1:
    #     resp['code'] =-1
    #     resp['msg'] ="需要code"
    #     return jsonify(resp)

    # 通MemberService获取openid
    # openid=MemberService.getWechatOpenId(code)
    if openid is None or len(openid) <1:
        resp['code'] = -1
        resp['msg'] = "调用微信出错"
        return jsonify(resp)

    # 小程序授权时需要的信息
    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''

    app.logger.info(nickname)
    app.logger.info(sex)
    app.logger.info(avatar)

    '''
    判断是否已经注册过，注册过直接返回信息
    '''
    bind_info=OauthMemberBind.query.filter_by(openid =openid,type=1).first()
    if not bind_info:
# 用户信息
        model_member = Member()
        # 获取用户名
        model_member.nickname = nickname
        model_member.sex = sex
        # 获取头像
        model_member.avatar = avatar
        # 获取随机字符串
        model_member.salt = MemberService.geneSalt()
        # 获取时间
        model_member.updated_time = model_member.created_time = getCurrentDate()
        # 将信息写入数据库
        db.session.add(model_member)
        # 提交 ：要获取自增字段所以需要立即提交
        db.session.commit()

# 建立绑定关系
        # 初始化类
        model_bind = OauthMemberBind()
        # model_bind.member_id等于 上面刚刚注册进去的id字段
        model_bind.member_id = model_member.id
        #
        model_bind.type = 1
        model_bind.openid = openid
        # 扩展字段
        model_bind.extra = ''
        model_bind.updated_time = model_bind.created_time = getCurrentDate()
        # 加入数据库
        db.session.add(model_bind)
        db.session.commit()

        # 将新变量直接复制给bind_info
        bind_info=model_bind

#返回信息
    # Member中查询信息
    member_info=Member.query.filter_by(id =bind_info.member_id).first()
    resp['msg'] = "已经绑定过，无需再注册"
    # 统一返回token给前台系统
    token = "%s#%s" % (MemberService.geneAuthCode(member_info), member_info.id)
    resp['data'] = {'token': token}
    return jsonify(resp)

# 授权登录
# checklogin:通过我们传过来的code来获取我们的openid通过绑定关系表中的openid来确定是否是已经存在的，
# 如果不存在则说说明没有绑定，我们就要进入我们的授权登录接口，如果已经绑定了但是还是获取不了member信息，
# 这种情况也要进行授权登录，有member信息以后生成一个token，token是我们未来请求所有api所需要的头部信息，
# 再通过头部信息来验证有效性。
@route_api.route("/member/check-reg",methods = ["GET","POST"])
def checkReg():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    # 从request.values里面得到变量
    req = request.values
    # 将所有后台信息进行统一展示 : 通过code可以获取用户的基本信息（session_key、openid）
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = "需要code"
        return jsonify(resp)

    openid = MemberService.getWechatOpenId(code)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = "调用微信出错"
        resp['data'] = openid
        return jsonify(resp)

    # 有openid的时候查看是否绑定关系
    bind_info = OauthMemberBind.query.filter_by(openid=openid, type=1).first()
    if not bind_info:
        resp['code'] = -1
        resp['msg'] = "未绑定"
        resp['data'] = openid
        return jsonify(resp)

    # 如果绑定了则可以取出用户信息
    member_info = Member.query.filter_by(id=bind_info.member_id).first()
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "未查询到绑定信息"
        resp['data'] = openid
        return jsonify(resp)

    # 产生token：所有api的头部信息
    token ="%s#%s"%(MemberService.geneAuthCode(member_info),member_info.id)
    resp['data'] ={'token':token}
    return jsonify(resp)

@route_api.route("/member/share",methods = ["GET","POST"])
def memberShare():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    req = request.values
    url = req['url'] if 'url' in req else ''
    member_info = g.member_info
    model_share = WxShareHistory()
    if member_info:
        model_share.member_id = member_info.id

    model_share.share_url = url
    model_share.created_time = getCurrentDate()
    db.session.add(model_share)
    db.session.commit()
    return jsonify(resp)


@route_api.route("/member/info",methods = ["GET","POST"])
def memberInfo():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    member_info = g.member_info
    resp['data']['info'] = {
        "nickname":member_info.nickname,
        "avatar_url":member_info.avatar
    }
    return jsonify(resp)